﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace G.SL.Net
{
    public class HttpFileUpload : HttpRequest
    {
        string boundary;
        public HttpFileUpload(string url)
            : base(url)
        {
            boundary = Guid.NewGuid().ToString();
            this.Method = HttpMethod.Post;
            base.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
        }

        private ParamCollection queryParams = new ParamCollection();
        /// <summary>
        /// Gets or sets parameters to be sent in the request query string.
        /// </summary>
        public virtual ParamCollection Params
        {
            get
            {
                return queryParams;
            }
        }

        public FileInfo[] Files { get; set; }

        protected override void WriteBody(System.IO.Stream reqStream)
        {
            foreach (var item in this.Params)
            {
                //sBuilder.Append("--");
                //sBuilder.Append(boundary);
                //sBuilder.Append("\r\n");
                //sBuilder.Append("Content-Disposition: form-data; name=\"" + item.Name + "\"\r\n\r\n");
                //sBuilder.Append(HttpUtility.UrlEncode(item.Value));
                //sBuilder.Append("\r\n");
                string str = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", boundary, item.Name, HttpUtility.UrlEncode(item.Value));
                reqStream.Write(str.GetBytes());
            }
            //split.Append("--");
            //split.Append(boundary);
            //split.Append("\r\n");
            //split.Append("Content-Disposition: form-data;name=\"pic\";filename=\"temp.jpg\"\r\n");
            //split.Append("Content-Type: image/jpg\r\n\r\n");
            //reqStream.Write(split.ToString().GetBytes());
            //reqStream.Write(FileBuffer);
            //reqStream.Write(("\r\n--" + boundary + "--\r\n").GetBytes());
            foreach (var f in Files)
            {
                string str = string.Format("--{0}\r\nContent-Disposition: form-data;name=\"{1}\";filename=\"{2}\"\r\nContent-Type:{3}\r\n\r\n", boundary, f.Name, f.FileName, f.ContentType);
                reqStream.Write(str.GetBytes());
                reqStream.Write(f.FileBuffer);
                reqStream.Write("\r\n".GetBytes());
            }
            reqStream.Write(("--" + boundary + "--\r\n").GetBytes());
         
        }
    }
}
